package application.thread;

import application.ListOption;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.concurrent.Semaphore;

/**
 *
 * @author Simão
 */
public class WriterThread extends Thread {

    private DataOutputStream dataOutpuStream;
    private Semaphore writerSemaphore;
    private ProtocolThread serverThread;

    WriterThread(DataOutputStream dataOutpuStream, Semaphore writerSemaphore, ProtocolThread serverThread) {
        this.dataOutpuStream = dataOutpuStream;
        this.writerSemaphore = writerSemaphore;
        this.serverThread = serverThread;
    }

    @Override
    public void run() {
        byte[] stream;
        System.out.println("A new WriterThread has stared.");
        while (true) {
            try {
                writerSemaphore.acquire();
            } catch (InterruptedException ex) {
                System.out.println("InterruptedException in synchronization point. Trying again.");
                continue;
            }
            stream = serverThread.useWriterList(ListOption.GET,null);
            System.out.println("Stream obtained from WriterList.");
            try {
                dataOutpuStream.writeInt(stream.length);
                dataOutpuStream.write(stream, 0, stream.length);
                dataOutpuStream.flush();
            } catch (IOException ex) {
                System.out.println("IOException in DataOutputStream. Discarding stream.");
                continue;
            }
            System.out.println("Message sucessfully sended.");
            serverThread.useWriterList(ListOption.REMOVE,null);
            System.out.println("Stream removed from WriterList.");
        }
    }
}
